package com.taobao.top.demo.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.taobao.top.demo.common.DemoConstant;
import com.taobao.top.demo.dataobject.Item;
import com.taobao.top.demo.dataobject.PropImg;
import com.taobao.top.demo.exception.DemoException;
import com.taobao.top.demo.getData.AddSku;
import com.taobao.top.demo.getData.GetItem;
import com.taobao.top.demo.getData.UpdateImgUtil;
import com.taobao.top.demo.getData.UpdateItem;

/**
 * 获得上传属性图片和别名
 * @author Jessica
 *
 */
public class UpdateImgServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置文件的缓存路径 
			String tempDir = "d:/tmp/"; 
			File file = new File(tempDir); 
			if(!file.exists()){ 
				file.mkdirs();
			}
			factory.setRepository(file);
			ServletFileUpload upload = new ServletFileUpload(factory); 
			upload.setHeaderEncoding("utf-8");
			
			//设置上传文件大小的上限，-1表示无上限 
			upload.setSizeMax(100*1024*1024);
			byte[] imgByte = new byte[1024];
			//获得并组装调用api时需要的参数
			String nick = (String)req.getSession().getAttribute("nick");
			String sessionKey = (String)req.getSession().getAttribute("sessionKey");
			String iid = "";
			String name = "";
			String temPath = "";
			PropImg propImg = new PropImg();		
			List fileItems = null;
			fileItems = upload.parseRequest(req);
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if(item.isFormField()) {
					//获得properties
					if(item.getFieldName().equals("properties")) {
						propImg.setProperties(item.getString());
					}
					//获得id
					if(item.getFieldName().equals("id")) {
						propImg.setPropimgId(item.getString());
					}
					//获得商品iid
					if(item.getFieldName().equals("iid")) {
						iid = item.getString();
					}
					//获得颜色属性别名
					if(item.getFieldName().equals("nameAlias")){
						propImg.setNameAlias(item.getString("utf-8"));
					}
					//获得vid，构造properties
					if(item.getFieldName().equals("vid")){
						propImg.setProperties(DemoConstant.PID+":"+item.getString());
					}
				}
				if (!item.isFormField()) {
					//获得上传图片的内容
					name = item.getName();
					temPath = tempDir + name;
					imgByte = item.get();
				}
			}
			//调用getItem方法，获得item
			Item item = GetItem.getItem(sessionKey, nick, iid);
			//获得属性图片的id，在做添加颜色属性图片时，颜色选取了已存在的颜色属性，则做更新操作
			List<PropImg> propImgs = item.getPropImgs();
			if(propImgs != null){
				for(int j = 0;j<propImgs.size();j++){
					PropImg pi = propImgs.get(j);
					if(pi.getProperties().equals(propImg.getProperties())){
						propImg.setPropimgId(pi.getPropimgId());
					}
					
				}
			}
			//更新颜色属性图片
			UpdateImgUtil.UpdateImg(iid, imgByte, sessionKey, propImg,name,temPath);
			//如果为添加属性图片，则添加sku
			if(propImg.getPropimgId()== null){
				AddSku.addSku(sessionKey, propImg.getProperties(), iid);
			}
			
			//更新或者是添加别名，更新item内容
			String nameAlias = item.getPropertyAlias();
			if(propImg.getNameAlias()!= null){
				String sb = nameAlias + ";" + propImg.getProperties()+ ":" + propImg.getNameAlias();	
				UpdateItem.updateItem(sessionKey,iid,sb);
			}
			//显示更新后的信息
			req.setAttribute("iid", iid);
			req.getRequestDispatcher("/operation/getIidServlet").forward(req, resp);
		} catch (FileUploadException e) {
			String errorMsg = "图片上传失败！";
			req.setAttribute("errorMsg", errorMsg);
			req.getRequestDispatcher("/error.jsp").forward(req, resp);
		} catch (DemoException e) {
			req.setAttribute("errorMsg", e.getMessage());
			req.getRequestDispatcher("/error.jsp").forward(req, resp);
		}
	}
}
